package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.*;
import com.tanhua.model.db.Question;
import com.tanhua.model.db.Settings;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.Visitors;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.SettingsVo;
import com.tanhua.model.vo.UserInfoVo;
import com.tanhua.model.vo.UserLikeListVo;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class UsersService {

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private QuestionApi questionApi;

    @DubboReference
    private SettingsApi settingsApi;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @DubboReference
    private BlackListApi blackListApi;

    //根据id查询
    public UserInfoVo findById(Long userId) {
        UserInfo userInfo = userInfoApi.findById(userId);

        //将UserInfo转化为UserInfovo并返回
        UserInfoVo vo = new UserInfoVo();

        BeanUtils.copyProperties(userInfo,vo); //将userInfo中同名，同类型的属性，复制到vo对象中

        if(userInfo.getAge() != null) {
            vo.setAge(userInfo.getAge().toString());
        }

        return vo;
    }

    //更新
    public void updateUserInfo(UserInfo userInfo) {
        userInfoApi.update(userInfo);
    }

    /**
     * 查询用户的通用设置
     */
    public SettingsVo settings() {
        SettingsVo vo = new SettingsVo();
        //需要用户id和手机号码
        vo.setId(UserHolder.getUserId());
        vo.setPhone(UserHolder.getMobile());
        //需要陌生人问题
        Question question = questionApi.findByUserId(UserHolder.getUserId());
        vo.setStrangerQuestion(question==null?"你喜欢java吗？":question.getTxt());
        //需要通知的开关
        Settings settings = settingsApi.findByUserId(UserHolder.getUserId());
        if(settings != null) {
            vo.setGonggaoNotification(settings.getGonggaoNotification());
            vo.setLikeNotification(settings.getLikeNotification());
            vo.setPinglunNotification(settings.getPinglunNotification());
        }
        return vo;
    }

    /**
     * 保存或者更新陌生人问题
     */
    public void saveQuestions(String content) {
        Long userId = UserHolder.getUserId();
        //1、根据当前用户id查询陌生人问题
        Question question = questionApi.findByUserId(userId);
        //2、判断是否存在
        if(question == null) {
            //2.1 如果不存在，构造数据保存
            question = new Question();
            question.setUserId(userId);
            question.setTxt(content);
            questionApi.save(question);
        }else {
            //2.2 如果存在，更新
            question.setTxt(content);
            questionApi.update(question);
        }
    }

    /**
     * 保存或者更新通知设置
     */
    public void saveSettings(Map map) {
        //1、获取请求的通知设置参数
        Boolean likeNotification = (Boolean) map.get("likeNotification");
        Boolean pinglunNotification = (Boolean) map.get("pinglunNotification");
        Boolean gonggaoNotification = (Boolean) map.get("gonggaoNotification");
        //2、获取当前的用户id
        Long userId = UserHolder.getUserId();
        //3、根据userId查询通知设置
        Settings settings = settingsApi.findByUserId(userId);
        //4、判断是否存在
        if(settings == null) {
            //4.1、不存在，保存
            settings = new Settings();
            settings.setPinglunNotification(pinglunNotification);
            settings.setGonggaoNotification(gonggaoNotification);
            settings.setLikeNotification(likeNotification);
            settings.setUserId(userId);
            settingsApi.save(settings);
        }else {
            //4.2、存在，更新
            settings.setPinglunNotification(pinglunNotification);
            settings.setGonggaoNotification(gonggaoNotification);
            settings.setLikeNotification(likeNotification);
            settingsApi.update(settings);
        }
    }

    //分页查询黑名单
    public PageResult blacklist(Integer page, Integer pagesize) {
        //1、获取当前用户id
        Long userId = UserHolder.getUserId();
        //2、调用API查询，返回IPage对象（mybatis-plus封装的pageBean）
        IPage iPage = blackListApi.findAll(userId,page,pagesize);
        //3、将Ipage中的属性赋值到PageResult中
        return new PageResult(page,pagesize,iPage.getTotal(),iPage.getRecords());
    }

    //移除黑名单
    public void deleteBlackList(Long blackUserId) {
        //1、获取当前用户id
        Long userId = UserHolder.getUserId();
        //2、调用API删除
        blackListApi.delete(userId,blackUserId);
    }

    @DubboReference
    private VisitorsApi visitorsApi;

    /**
     * type：
     *     1：查询相互喜欢
     *     2：查询喜欢的
     *     3：查询粉丝
     *     4；查询访客
     */
    public PageResult friends(Integer type, Integer page, Integer pagesize) {
        if(type != 4) {
            //剩下的查询，以后实战实现
            return new PageResult();
        }
        //1、获取用户id
        Long userId = UserHolder.getUserId();
        //2、调用API根据id查询用户数据  List<Vistors>
        List<Visitors> list = visitorsApi.findByUserId(userId,page,pagesize);
        //3、判断list是否为空
        if(list == null || list.size()<=0) {
            return new PageResult();
        }
        //4、一个Vistors构造一个VO
        //获取list中的所有访客id
        List<Long> ids = CollUtil.getFieldValues(list, "visitorUserId", Long.class);
        //查询所有访客的信息
        Map<Long, UserInfo> map = userInfoApi.findByIds(ids);
        List<UserLikeListVo> vos = new ArrayList<>();
        for (Visitors visitors : list) {
            UserInfo userInfo = map.get(visitors.getVisitorUserId());
            UserLikeListVo vo = UserLikeListVo.init(userInfo, visitors);
            vos.add(vo);
        }
        //记录访问的时间到redis中
        Long date = System.currentTimeMillis();
        String key = Constants.VISITORS_USER+userId;
        redisTemplate.opsForValue().set(key,date.toString());
        return new PageResult(page,pagesize,0l,vos);
    }
}
